<template>
  <div class="login_container">
    <div class="login_box">
      <!-- 头像区域 -->
      <div class="avatar_box">
        <img src="../../../assets/img/yonghu.png" alt="" />
      </div>

      <!-- 登录表单区域 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        label-width="0px"
        class="login_form"
      >
        <!-- 用户名 -->
        <el-form-item>
          <el-input
            v-model="loginForm.userTel"
            prefix-icon="iconfont icon-user"
            placeholder="请输入手机号码"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item>
          <el-input
            v-model="loginForm.password"
            prefix-icon="iconfont icon-3702mima"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <!-- 按钮区域 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="login" plain>登录</el-button>
          <el-button @click="setRegistDialogVisible = true" plain
            >注册</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 注册页面区域 -->
    <el-dialog
      title="注册账户"
      :visible.sync="setRegistDialogVisible"
      width="50%"
      @close="setRegistDialogClose"
      :close-on-click-modal="false"
    >
      <!-- 注册表 -->
      <el-form
        :model="registerForm"
        ref="registruleFormRef"
        label-width="100px"
      >
        <!-- 增加方法手机输入框在失去焦点的时候，自动校验手机号是否存在 -->
        <el-form-item label="电话" size="mini">
          <el-input v-model="registerForm.userIdTel"></el-input>
        </el-form-item>
        <el-form-item label="密码" size="mini">
          <el-input
            type="password"
            v-model="registerForm.userPassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" size="mini">
          <el-input
            type="password"
            v-model="registerForm.confirmPassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" size="mini">
          <el-input v-model="registerForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="姓名" size="mini">
          <el-input v-model="registerForm.userRealName"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" size="mini">
          <el-input v-model="registerForm.eMail"></el-input>
        </el-form-item>
        <!-- 生日 -->
        <el-form-item label="生日">
          <el-date-picker
            v-model="registerForm.birthday"
            type="date"
            size="mini"
            placeholder="选择出身年份"
          >
          </el-date-picker>
        </el-form-item>
        <!-- 地址 -->
        <el-form-item label="地址">
          <el-cascader
            size="mini"
            :options="options"
            v-model="registerForm.location"
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <!-- 按钮组 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="registRegisterForm">确 定</el-button>
        <el-button @click="setRegistDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//地址的接口
import { getAllAddress } from "network/address";
// 统计报表网络请求
import { getDataChart,getOrderByUser } from "network/statistic";
// 卡片接口
import { getAllCard,getCard } from "network/cardpack";
// 引用用户信息
import { getSelectUser } from "network/account";
// 省市区三级联动
import { regionData } from "element-china-area-data";
// 请求登录参数的网络请求
import { getUserLogin, getExist, getRegister } from "network/login";
export default {
  name: "LoginUser",
  data() {
    // 存取卡包数据的

    // 取出接口里面的数组

    // // // 验证邮箱规则
    // let checkEmail = (rule, value, cb) => {
    //   const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    //   if (regEmail.test(value)) {
    //     //合法
    //     return cb();
    //   }
    //   cb(new Error("请输入合法的邮箱"));
    // };

    // // 验证手机号的规则
    // let checkMobile = (rule, value, cb) => {
    //   // 验证手机号的正则表达式
    //   const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
    //   if (regMobile.test(value)) {
    //     return cb();
    //   }
    //   cb(new Error("请输入合法的手机号"));
    // };

    // // 验证手机号是否重复规则
    // let checkMobileRepetition = (rule, value, cb) => {
    //   // 发送请求到后端查询手机号是否重复
    //   // 成立
    //   if (regMobile.test(value)) {
    //     return cb();
    //   }
    //   // 不成立
    //   cb(new Error("请输入合法的手机号"));
    // };

    // 设置日期选择规则，今天之前的日期

    return {
      //从接口拿到的领取卡包的卡片信息
      cardFrom:[],
      //从接口拿到的订单数据
      orderData:[],
      //从接口拿到的地址的数据
      userAddresses: [],
      // 存储从接口拿到的统计报表数据
      yearConsume: [],
      //统计报表组件中的三个小卡片的内容
      totalCardInfo:["2021.05.10", 1033],
      //拿到统计图的接口数据
      totalAll: [],
      figure1: ["交通出行"],
      figure2: ["休闲娱乐"],
      figure3: ["健身运动"],
      figure4: ["其他"],
      figure5: ["医药健康"],
      figure6: ["学习教育"],
      figure7: ["服饰"],
      figure8: ["生活商超"],
      figure9: ["酒店度假"],
      figure10: ["饮食"],
      // 取出接口里面的数组
      cardInfo: [],
      card: [],
      // 会员卡列表
      cardList: [],
      //注册弹出框显示的控制
      setRegistDialogVisible: false,

      //登录表单的数据绑定对象
      loginForm: {
        // 解决输入框type= number 出现上下箭头
        userTel: "13645220001",
        password: "12345",
      },

      // 用户注册的数据绑定对象
      registerForm: {
        userIdTel: "",
        userName: "",
        userPassword: "",
        confirmPassword: "",
        userRealName: "",
        birthday: "",
        location: "",
        eMail: "", // 用户所在地
      },

      // 登陆表单验证规则对象
      // loginFormRules: {
      //   // 验证用户名是否合法
      //   userTel: [
      //     { required: true, message: "请输入手机号", trigger: "blur" },
      //     { pattern: /^\d{11}$/, message: "手机号不符法", trigger: "blur" },
      //   ],
      //   // 验证密码是否合法
      //   password: [
      //     { required: true, message: "请输入密码", trigger: "blur" },
      //     {
      //       min: 4,
      //       max: 20,
      //       message: "长度在 4 到 20 个字符",
      //       trigger: "blur",
      //     },
      //   ],
      // },

      // 用户注册的表单验证对象
      // registUserRules: {
      //   userName: [
      //     {
      //       required: true,
      //       message: "请输入您的昵称",
      //       trigger: "blur",
      //     },
      //   ],
      //   userRealName: [
      //     {
      //       required: true,
      //       message: "请输入您的昵称",
      //       trigger: "blur",
      //     },
      //   ],
      //   userPassword: [
      //     {
      //       required: true,
      //       message: "请输入密码",
      //       trigger: "blur",
      //     },
      //     {
      //       min: 3,
      //       max: 10,
      //       message: "长度在 3 到 10 个字符",
      //       trigger: "blur",
      //     },
      //   ],
      //   userIdTel: [
      //     {
      //       required: true,
      //       message: "请输入电话号码",
      //       trigger: "blur",
      //     },
      //     {
      //       validator: checkMobile,
      //       trigger: "blur",
      //     },
      //     {
      //       validator: checkMobileRepetition,
      //       trigger: "blur",
      //     },
      //   ],
      //   eMail: [
      //     { required: true, message: "请输入邮箱", trigger: "blur" },
      //     { validator: checkEmail, trigger: "blur" },
      //   ],
      // },

      // 三级联动
      options: regionData,
    };
  },
  methods: {
    //计算统计报表
    calculate(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10) {
      // 计算total all数组的总值
      let sum = 0 ;
      for (let i = 1; i <= 12; i++) {
        this.totalAll[i - 1] =
          parseFloat(arr1[i]) +
          parseFloat(arr2[i]) +
          parseFloat(arr3[i]) +
          parseFloat(arr4[i]) +
          parseFloat(arr5[i]) +
          parseFloat(arr6[i]) +
          parseFloat(arr7[i]) +
          parseFloat(arr8[i]) +
          parseFloat(arr9[i]) +
          parseFloat(arr10[i]);

        // 保留两位小数，但是变成了字符串
        sum += this.totalAll[i-1];
        this.totalAll[i - 1] = this.totalAll[i - 1].toFixed(2);
      }
      // console.log('总计'+sum);
      this.totalCardInfo.push(sum)
      
    },
    //定义函数将数组每位保留两位小数

    // 登录
    login() {
      let _this = this;
      this.$refs.loginFormRef.validate(async (valid) => {
        let formdata = new FormData();
        formdata.append("userTel", this.loginForm.userTel);
        formdata.append("password", this.loginForm.password);
        if (!valid) return;
        /**
         * 网络请求相关方法
         * 登录的请求
         */
        getUserLogin(formdata).then((res) => {
          // 如果可以登录
          // console.log('它的值是'+res.headers.token);
          if (res != "406") {
            // return _this.$message.error('登陆失败')
            window.sessionStorage.setItem("token", res.headers.token);
            // window.sessionStorage.setItem("userinfo", res.data.data);
            // 将用户名存储到vuex中
            this.$store.state.UserTelId = this.loginForm.userTel;
            //
            let formdataSee = new FormData();
            formdataSee.append("userTel", this.$store.state.UserTelId);
            _this.$message.success("登录成功");
            _this.$router.push("/userhome");
            getSelectUser(formdataSee).then((res) => {
              // 如果正确请求
              // console.log(res);
              if (res !== "406") {
                // 赋值
                window.sessionStorage.setItem(
                  "userName",
                  res.data.data.userName
                );
                window.sessionStorage.setItem(
                  "userRealName",
                  res.data.data.userRealName
                );
                window.sessionStorage.setItem("email", res.data.data.eMail);
                window.sessionStorage.setItem(
                  "userIdTel",
                  res.data.data.userTel
                );
                window.sessionStorage.setItem(
                  "birthday",
                  res.data.data.birthday
                );
                window.sessionStorage.setItem(
                  "location",
                  res.data.data.location
                );
              }
            });

            // 将卡包的数据存储到sessionStorage中
            let cardSee = new FormData();
            cardSee.append("userIdTel", this.$store.state.UserTelId);

            //调用获取卡片的接口
            getAllCard(cardSee).then((res) => {
              for (let i = 0; i < res.data.data.length; i++) {
                // 将接口拿到的数据拷贝到card数组中
                this.card.push(res.data.data[i]);
              }
              for (let i = 0; i < this.card.length; i++) {
                this.cardList.push({
                  cardId: this.card[i].card_id,
                  cardName: this.card[i].card_name,
                  cardComment: this.card[i].card_comment,
                  scoreNumber: 100,
                  cardPicture:
                    "http://qtpd7mr9w.hn-bkt.clouddn.com/" +
                    this.card[i].card_picture,
                });
              }
              // 将卡片的信息存储到sessionStorage里面
              sessionStorage.setItem("cardInfo", JSON.stringify(this.cardList));
              //刷新页面写卡片这因为是首页
              // location.reload();
            });

            /**
             * 网络请求统计报表
             */
            let statsticSee = new FormData();
            statsticSee.append("userIdTel", this.$store.state.UserTelId);
            // getDataChart(statsticSee).then(res=>{
            //   console.log(res.data.reportByMonth.length);
            //   for(let i = 0 ; i<res.data.reportByMonth.length;i++){
            //     // console.log(res.data.reportByMonth[i].months.substring(6));
            //     // 拿到柱状图的数据(统计数据)
            //     if(res.data.reportByMonth[i].months.substring(0,4) == '2019'){
            //       this.totalAll[parseInt(res.data.reportByMonth[i].months.substring(5))-1] = res.data.reportByMonth[i].total;
            //     }
            //   }
            //   // console.log(this.totalAll);
            // })

            getDataChart(statsticSee).then((res) => {
              // console.log(res.data.data[1]);
              this.yearConsume.push(res.data.data[1]);
              //  console.log(this.yearConsume[0]["2019"][0]["交通出行"][1]);
              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["交通出行"].length;
                i++
              ) {
                this.figure1.push(
                  this.yearConsume[0]["2019"][0]["交通出行"][i].toFixed(2)
                );
              }

              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["休闲娱乐"].length;
                i++
              ) {
                this.figure2.push(
                  this.yearConsume[0]["2019"][0]["休闲娱乐"][i].toFixed(2)
                );
              }

              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["健身运动"].length;
                i++
              ) {
                this.figure3.push(
                  this.yearConsume[0]["2019"][0]["健身运动"][i].toFixed(2)
                );
              }

              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["其他"].length;
                i++
              ) {
                this.figure4.push(
                  this.yearConsume[0]["2019"][0]["其他"][i].toFixed(2)
                );
              }

              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["医药健康"].length;
                i++
              ) {
                this.figure5.push(
                  this.yearConsume[0]["2019"][0]["医药健康"][i].toFixed(2)
                );
              }
              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["学习教育"].length;
                i++
              ) {
                this.figure6.push(
                  this.yearConsume[0]["2019"][0]["学习教育"][i].toFixed(2)
                );
              }

              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["服饰"].length;
                i++
              ) {
                this.figure7.push(
                  this.yearConsume[0]["2019"][0]["服饰"][i].toFixed(2)
                );
              }
              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["生活商超"].length;
                i++
              ) {
                this.figure8.push(
                  this.yearConsume[0]["2019"][0]["生活商超"][i].toFixed(2)
                );
              }

              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["酒店度假"].length;
                i++
              ) {
                this.figure9.push(
                  this.yearConsume[0]["2019"][0]["酒店度假"][i].toFixed(2)
                );
              }

              for (
                let i = 0;
                i < this.yearConsume[0]["2019"][0]["饮食"].length;
                i++
              ) {
                this.figure10.push(
                  this.yearConsume[0]["2019"][0]["饮食"][i].toFixed(2)
                );
              }
              this.calculate(
                this.figure1,
                this.figure2,
                this.figure3,
                this.figure4,
                this.figure5,
                this.figure6,
                this.figure7,
                this.figure8,
                this.figure9,
                this.figure10
              );
              // console.log(this.figure1);
              //将统计报表数据存储到sessionStorage中
              // console.log(this.totalCardInfo);
              

              sessionStorage.setItem("figure1", JSON.stringify(this.figure1));
              sessionStorage.setItem("figure2", JSON.stringify(this.figure2));
              sessionStorage.setItem("figure3", JSON.stringify(this.figure3));
              sessionStorage.setItem("figure4", JSON.stringify(this.figure4));
              sessionStorage.setItem("figure5", JSON.stringify(this.figure5));
              sessionStorage.setItem("figure6", JSON.stringify(this.figure6));
              sessionStorage.setItem("figure7", JSON.stringify(this.figure7));
              sessionStorage.setItem("figure8", JSON.stringify(this.figure8));
              sessionStorage.setItem("figure9", JSON.stringify(this.figure9));
              sessionStorage.setItem("figure10", JSON.stringify(this.figure10));
              sessionStorage.setItem("totalAll", JSON.stringify(this.totalAll));
              sessionStorage.setItem("totalCardInfo", JSON.stringify(this.totalCardInfo));
            });
            //查看收货地址接口
            let addressSee = new FormData();
            addressSee.append("userTel", this.$store.state.UserTelId);
            // 获取用户的收货地址
            getAllAddress(addressSee).then((res) => {
              // console.log(res.data.data);
              for(let i = 0 ; i < res.data.data.length; i++){
                 this.userAddresses.push({
                   addressId:res.data.data[i].addressId,
                   userIdTel:res.data.data[i].userIdTel,
                   recipientsName:res.data.data[i].recipientsName,
                   recipientsTel:res.data.data[i].recipientsTel,
                   recipientsLocation:res.data.data[i].recipientsLocation,
                   recipientsAddress:res.data.data[i].recipientsAddress,
                   recipientsComment:res.data.data[i].recipientsComment
                 })
              }
              sessionStorage.setItem("userAddresses", JSON.stringify(this.userAddresses));
            });

            //获取用户的所有订单
            let orderSee = new FormData();
            orderSee.append("userIdTel", this.$store.state.UserTelId);
            getOrderByUser(orderSee).then(res=>{
              
              for(let i = 0 ; i < res.data.data.length; i++){
                 this.orderData.push({
                   orderId:res.data.data[i].orderId,
                   orderName:res.data.data[i].orderName,
                   orderTime:res.data.data[i].orderTime,
                   totalPrice:res.data.data[i].totalPrice,
                   cardPackId:res.data.data[i].cardPackId,
                   couponPackId:res.data.data[i].couponPackId,
                   orderComment:res.data.data[i].orderComment
                 })
              }
              // 将订单的信息存储到sessionStorage里面
              // console.log(this.orderData);
              sessionStorage.setItem("orderInfo", JSON.stringify(this.orderData));
            })

            //获取 领取卡包的所有卡片
            getCard().then(res=>{
              // console.log(res.data.data.length);
              for(let i = 0 ; i < res.data.data.length ; i++){
                this.cardFrom.push({
                  card_comment:res.data.data[i].card_comment,
                  card_type_id:res.data.data[i].card_type_id,
                  card_picture:res.data.data[i].card_picture,
                  card_name:res.data.data[i].card_nameres,
                  merchant_picture:res.data.data[i].merchant_picture,
                  merchant_name:res.data.data[i].merchant_name,
                  merchant_id:res.data.data[i].merchant_id,
                  merchant_comment:res.data.data[i].merchant_comment,
                  card_id:res.data.data[i].card_id,
                  card_type_name:res.data.data[i].card_type_name,
                })
              }
      
              sessionStorage.setItem("cardFrom", JSON.stringify(this.cardFrom));
            })


            //获取所有的卡片
          } else {
            _this.$message.error("登录失败");
          }
        });
      });
    },

    // 转换时间格式
    changeTimeStyle(updateTime) {
      let date = new Date(updateTime);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      const time = y + "-" + m + "-" + d;
      return time;
    },

    // 注册
    registRegisterForm() {
      let _this = this;
      console.log(this.registerForm);
      // 转变时间格式
      const time = this.changeTimeStyle(this.registerForm.birthday);
      // 检测用户是否存在的表单值变量

      //表单验证
      this.$refs.registruleFormRef.validate(async (valid) => {
        let formdata = new FormData();
        formdata.append("userName", this.registerForm.userName);
        formdata.append("userPassword", this.registerForm.userPassword);
        formdata.append("userIdTel", this.registerForm.userIdTel);
        formdata.append("userRealName", this.registerForm.userRealName);
        formdata.append("eMail", this.registerForm.eMail);
        formdata.append("birthday", time);
        formdata.append("location", this.registerForm.location);

        // 查询
        let formdataR = new FormData();
        formdataR.append("userTel", this.registerForm.userIdTel);

        // 是否给予注册权限

        getExist(formdataR)
          .then((res) => {
            // 用户存在
            if (res !== "406") {
              _this.$message.error("您已经注册了请登录");
            }
          })
          .catch((err) => {
            // 没有请求到接口
          });

        /**
         * 注册用户
         */
        getRegister(formdata).then((res) => {
          if (res === "407") {
            _this.$message.error("注册内容填写失败请检查");
          } else {
            console.log(res);
            _this.$message.success("注册成功");
            window.sessionStorage.setItem("token", res.token);
            window.sessionStorage.setItem("userinfo", res);
          }
        });

        // getRegister(formdata).then(res=>{

        // }).catch(err => {

        // })
      });
    },

    // 注册表单中的取消按钮
    setRegistDialogClose() {
      // 删除
      this.$refs.registruleForm.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
// 解决 element ui 输入框为数字的上下箭头
.login_container {
  background-color: #09435b;
  height: 100%;
}

.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  // 居中语法
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  .avatar_box {
    height: 130px;
    width: 130px;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    // 父元素的高度
    transform: translate(-50%, -50%);
    background-color: #fff;

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      // background-color: #eee;
    }
  }
}
.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  // 怪异盒模型防止padding
  box-sizing: border-box;
}
.btns {
  display: flex;
  // 居右对齐
  justify-content: flex-end;
}
</style>